<?php

namespace app\index\controller;

use think\Exception;
use org\Upload as UploadTools;
use app\commons\model\UploadFile;
use think\facade\Env;

class Upload
{
    /**
     * 上传视频/音频/图片
     * @return \think\response\Jsonp|void
     */
    public function create() {
        try {
            $exts = ['jpeg', 'jpg', 'png','mp3','mp4'];
            $config = [
                'exts' => $exts,
                'maxSize' => 10485760,//大小限制(10m)
                'saveName' => ['uniqid', time()],
            ];
            $upload = new UploadTools($config, "Local", ['type'=>'Local']);
            $fileinfo = $upload->upload($_FILES);
            if(empty($fileinfo)) throw new Exception($upload->getError());
            $dest = [
                'hash' => $fileinfo['file']['md5'],
                'key' => '/Uploads/' . $fileinfo['file']['savepath'] . $fileinfo['file']['savename'],
                'ext' => $fileinfo['file']['ext']
            ];
//            dump(file_get_contents(Env::get('root_path').'public'.$dest['key']));die;
            $fileInfos = UploadFile::where(['hash'=>$dest['hash'],'ext'=>$dest['ext']])->field(['hash','key','ext','id','type','member_id'])->find();
            if(!$fileInfos){
                $createData = $dest;
                $createData['member_id'] = session('merch')->id;
                $createData['type'] = 'merch';
                $res = UploadFile::create($createData);
                if(!$res) throw new Exception('上传文件失败！');
                $createData['url'] = images_url($createData['key']);
                return jsonp($createData);
            }
            if (file_exists(Env::get('root_path').'public'.$fileInfos['key'])) {
                unlink(Env::get('root_path').'public'.$dest['key']);
                $fileInfos['url'] = images_url($fileInfos['key']);
                return jsonp($fileInfos);
            }
            $res = UploadFile::where(['id'=>$fileInfos['id']])->update(['key' => $dest['key']]);
            if(!$res) throw new Exception('上传文件失败2！');
            $dest['url'] = images_url($dest['key']);
            return jsonp($dest);
        }catch (Exception $exception){
            return jsonp_error(422,$exception->getMessage());
        }
    }
}